#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QTableView>
#include <QSqlQuery>
#include <QSqlError>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("./Library_313.db");
    if (db.open()) {
        qDebug() << "Database opened successfully!";

        QSqlQuery query(db);
        if (query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='readers'")) {
            if (query.next()) {
                qDebug() << "Table readers exists.";

                QSqlTableModel *model = new QSqlTableModel(this, db);
                if(model->rowCount()>=1)
                    qDebug("select!");
                QString filter = QString("学号 LIKE \"\%%1\%\"").arg(this->ui->lineEdit->text());
                model->setTable("readers");
                model->setFilter(filter);
                model->select();

                QTableView *m_table = this->ui->tableView;
                m_table->setModel(model);

                // 假设密码列是第五列（索引从0开始）
                m_table->horizontalHeader()->setSectionHidden(5, true); // 隐藏第五列
            } else {
                qDebug() << "Table readers does not exist.";
            }
        } else {
            qDebug() << "Failed to execute query:" << query.lastError().text();
        }
    } else {
        qDebug() << "Failed to open database!";
    }
}

